import React, { useState, useEffect, useRef } from "react";
import { connect, useDispatch, history } from "umi";
import { Card, message, Switch, Modal } from "antd";
import FormData from "./form";

import {
  XHbutton,
  XHmodal,
  XHselectForm,
  XHoperate,
  XHtable,
} from "@/components/xh-components/index";
import {
  GetDailtAPI,
  GetListAPI,
  DelDataAPI,
  AddDataAPI,
  EditDataAPI,
  UpdateDefaultValueAPI,
} from "@/api/system/printConfig";
const PrintConfigPage = (props) => {
  const { confirm } = Modal;
  // 列表枚举
  const columns = [
    { title: "模板名称", dataIndex: "printName", key: "printName" },
    { title: "打印单据", dataIndex: "printCorrelationName", key: "printCorrelationName" },
    {
      title: "是否默认",
      dataIndex: "defaultValue",
      key: "defaultValue",
      render: (_, record) => {
        return (
          <Switch
            checked={record.defaultValue == "0"}
            checkedChildren="启用"
            unCheckedChildren="禁用"
            defaultChecked
            onClick={() => showChangeStatusConfirm(record)}
          />
        );
      },
    },
    {
      title: "操作",
      width: "15%",
      render: (val) => {
        return (
          <XHoperate
            list={[
              {
                label: "修改",
                emit: () => edit(val),
                permissions: "system:printConfig:edit",
              },
              {
                label: "删除",
                danger: true,
                showMsg: true,
                emit: () => del(val),
                permissions: "system:printConfig:remove",
              },

              {
                label: "查看",
                emit: () => see(val),
                permissions: "system:printConfig:query",
              },
            ]}
          />
        );
      },
    },
  ];

  // 各种状态
  const [state, setState] = useState({
    loading: false,
    show: false,
    title: "新增",
    btnLoading: false,
    total: 0,
  });

  // 列表参数
  const [query, setQuery] = useState({
    pageNum: 1,
    pageSize: 10,
  });

  // 表格数据
  const [tableData, setTableData] = useState({
    data: [],
    total: 0,
  });

  // 表单ref
  const formRef = useRef(null);

  //单挑数据
  const [dataForm, setDataForm] = useState({});

  //新增弹窗
  const add = () => {
    setState({
      ...state,
      show: true,
      title: "新增",
    });
  };

  //修改弹窗
  const editDic = async (val) => {
    try {
      dispatch({
        type: "appConfig/loading",
      });
      const { data: res } = await GetViewAPI(val.roleId);

      setDataForm(res);
      setState({
        ...state,
        show: true,
        title: "修改",
      });
    } catch (err) {
      console.log(err);
    } finally {
      dispatch({
        type: "appConfig/closeLoading",
      });
    }
  };

  //关闭弹窗
  const close = () => {
    setDataForm({}); //清空表单
    setState({
      ...state,
      show: false,
    });
  };

  //新增确认
  const addSub = async () => {
    const res = await formRef.current.validateFields();
    if (!res) return;
    try {
      setState({
        ...state,
        btnLoading: true,
      });
      await AddDataAPI(res);
      message.success("新增成功!");
      close();
      getList();
    } catch (err) {
      setState({
        ...state,
        btnLoading: false,
      });
    } finally {
    }
  };

  // 修改确认
  const editSub = async () => {
    const res = await formRef.current.validateFields();
    if (!res) return;
    try {
      setState({
        ...state,
        btnLoading: true,
      });
      await EditDataAPI(res);
      message.success("修改成功!");
      close();
      getList();
    } catch (err) {
    } finally {
      setState({
        ...state,
        btnLoading: false,
      });
    }
  };

  //删除
  const del = async (val) => {
    try {
      DelDataAPI(val.roleId).then((resp) => {
        message.success("删除成功！");
        getList();
      });
    } catch (error) {}
  };

  //改变状态时
  const showChangeStatusConfirm = async (record) => {
    let text = record.defaultValue == "1" ? "启用" : "取消";
    const newStatus = record.defaultValue == "0" ? "1" : "0";
    confirm({
      centered: true,
      cancelText: "取消",
      okText: "确定",
      title: `确认要${text}默认吗？`,
      onOk() {
        UpdateDefaultValueAPI({ printId: record.printId, defaultValue: newStatus }).then((resp) => {
          if (resp.code === 200) {
            message.success(`${text}成功!`);
            getList();
          }
        });
      },
    });
  };

  //分配用户
  const authUser = (val) => {
    history.push(`/system/role-auth/user?id=${val.roleId}`);
  };

  //分页改变时
  const onShowSizeChange = (current, pageSize) => {
    setQuery({ pageNum: current, pageSize: pageSize });
  };

  //分页改变时
  const totalonChange = (current, pageSize) => {
    setQuery({ pageNum: current, pageSize: pageSize });
  };

  //数据权限弹窗
  const datascope = () => {};

  //查询
  const selectSubmit = (val) => {
    console.log(val, "val");
  };

  //重置
  const selectReset = (val) => {
    console.log(val, "val");
  };

  // 获取表格数据
  const getList = async () => {
    try {
      setState({
        loading: true,
      });
      const res = await GetListAPI(query);
      setTableData({
        data: res.rows,
        total: res.total,
      });
    } catch (err) {
      console.log(err);
    } finally {
      setState({
        loading: false,
      });
    }
  };

  return (
    <div className="app-container">
      <Card>
        <XHselectForm
          list={[
            { label: "测试输入框", type: "输入框", model: "name" },
            { label: "测试时间", type: "时间日期", model: "time" },
          ]}
          selectSubmit={selectSubmit}
        />
        <XHbutton
          list={[
            {
              label: "新增",
              emit: () => add(),
            },
          ]}
        />
        <XHtable
          loading={state.loading}
          columns={columns}
          renderCell={() => ""}
          rowSelection={null}
          dataSource={tableData.data}
          pagination={(val) => {
            getList({
              ...query,
              ...val,
            });
          }}
        />
        <XHmodal
          open={state.show}
          title={state.title}
          loading={state.btnLoading}
          width={700}
          ok={() => (state.title == "新增" ? addSub() : editSub())}
          no={() => close()}
          body={<FormData ref={formRef} data={dataForm} title={state.title} />}
        />
      </Card>
    </div>
  );
};
export default connect((state) => ({ user: state.user }))(PrintConfigPage);
